import { useEffect, useRef, useState } from "react"
import {NavBar ,Icon,WhiteSpace,Popover,InputItem,Button, Toast} from 'antd-mobile'
import {connect} from 'react-redux'

import {get_message} from '../../../../../network/freind'

import {Diaolog , Diaolog_2} from '../../../../../common/Diaolog'

import './index.css'

import df from '../../../../../statics/img/df.svg'



const FriendChat = ({ 
  location :{state:{avatar,username:itename}},
  history,
  username,
  useravatar,
  wsurl
}) =>{

    const [itname,setitname] = useState(itename)
    const [itavatar ,setitavatar] = useState(avatar)
    const [visible , setvisible] = useState(false)
    const [msg,setmsg] = useState()
    const [msglist,setmsglist] = useState([])
    const [websocket,setwebsocket] = useState(new WebSocket(wsurl))


    const myref = useRef()

    useEffect(()=>{

      websocket.onopen = function() {
          console.log("连接成功");
      }

      websocket.onclose = function() {
          console.log("退出连接");
      }

      websocket.onmessage = function(event) {

        console.log(event.data);
        let obj = JSON.parse(event.data);
        if(obj.from === itname){
          const record_list = [...msglist]
          const msg = obj.data
          const date = new Date().toLocaleTimeString()
          const type = 2 
          const ava = itavatar
          record_list.push({
            msg,
            type,
            avatar:ava,
            date,
          })
          setmsglist(record_list)
        }
      }

      return ()=>{
          websocket.close();
      }
  },[]) 

    useEffect(()=>{
        
        console.log(username);
        console.log(useravatar);
        const get_friend_msg = async()=>{
            const res = await get_message()
            const data = res.data
            if( itname in data && data[itname][1]){
              const msg_record = data[itname][1]
              const record_list = []
              msg_record.forEach(item => {
                const msg = item.data
                const date = item.date
                let type,ava
                if(item.from === username){
                  type = 1
                  ava = useravatar
                }else{
                  type =2
                  ava = avatar
                }
                console.log(ava);
                record_list.push({
                  msg,
                  type,
                  avatar:ava,
                  date,
                })
              });
              setmsglist(record_list)
            }
        }
        get_friend_msg()
    },[])



    const handleVisibleChange = (visible) => {
        setvisible(visible)
      };

    const onSelect = (opt) => {
  
        setvisible(false)
        const delete_msg = {
          from : username,
          to : itename,
          type : 3,
          data : null
        }
        websocket.send(JSON.stringify(delete_msg));
        history.goBack()
      };

    const on_send =()=>{
      
      if(!msg) {
        Toast.info('不能发送空信息！',1)
        return 
      }

      //websocket发送
      const msg_send = {
        'from': username,
        'data': msg,
        'to': itename,
        'type': 1
      }
      
      websocket.send(JSON.stringify(msg_send));

      //界面显示
      const date = new Date().toLocaleTimeString()
      const msgitem = {
        msg,
        type:1,
        avatar:useravatar,
        date,
      }
      const new_list = [...msglist]
      new_list.push(msgitem)
      setmsglist(new_list)
      myref.current.state.value = ""


        
    }

    const on_change=(msg)=>{
        
        setmsg(msg);
    }

    const on_clear = () =>{
        
    }

    return <div className = "friendchat">
        <NavBar
            mode="dark"
            icon={<Icon type="left" />}
            onLeftClick={() => {history.goBack()}}
            rightContent={ 
            <Popover 
                overlayClassName="fortest"
                overlayStyle={{ color: 'currentColor' }}
                visible={visible}
                overlay={[
                  (<Popover.Item key="4" value="deletefriend"  data-seed="deletefriend">删除好友</Popover.Item>)
                ]}
                align={{
                  overflow: { adjustY: 0, adjustX: 0 },
                  offset: [-10, 0],
                }}
                onVisibleChange={handleVisibleChange}
                onSelect={onSelect}
              >
                  <div style={{
                  height: '100%',
                  padding: '0 15px',
                  marginRight: '-15px',
                  display: 'flex',
                  alignItems: 'center',
                }}
                >
                  <img  src={df} height= {20} />
                </div>
              </Popover>}
            
            >
        {itname}
        </NavBar>
        <div className = "chat_content">
          {msglist.map((item)=>{
            if(item.type === 1){
              return <Diaolog key={item.date} info={item}/>
            }
            else{
              return <Diaolog_2 key={item.date} info={item}/>
            }
           
          })}
        </div>
        <div className='chat_foot'>
            <InputItem
            ref = {myref}
            className = 'msg_input'
            defaultValue = {msg} 
            onChange = {on_change}
            
            />
            <Button onClick={on_send}  className='send_button'>发送</Button>
        </div>
     
    </div>
}

const mapState2Props = (state)=>({
    username : state.getIn(['login','usr']),
    useravatar : state.getIn(['login','avatar']),
    wsurl : state.getIn(['login','ws_url'])
})

const mapDispatch2Props = {
    
}


export default connect(mapState2Props,mapDispatch2Props)(FriendChat)